package com.luyou.smart.framewortk;

import com.luyou.smart.framewortk.helper.ConfigHelper;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.net.URISyntaxException;

public class TomcatTest {

    public static void main(String[] args) throws URISyntaxException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8888);
        tomcat.setHostname("localhost");
        // Tomcat 9.0 必须调用 Tomcat#getConnector() 方法之后才会监听端口
        tomcat.getConnector();
        Context context = tomcat.addContext("/smart", ClassLoader.getSystemResource("").getPath());
        /**
         * 添加一个监听器
         * Tomcat.DefaultWebXmlListener() 该监听器会获取一些已配置好的设置，适用于程序化配置
         * Tomcat.ExistingStandardWrapper(Servlet existing) 该监听器使用自定义的Servlet，增强对Servlet的控制
         * Tomcat.FixContextListener() 该监听器在不使用web.xml时为必须项
         */
        context.addLifecycleListener(new Tomcat.FixContextListener());
        Wrapper dispatcherWrapper = Tomcat.addServlet(context, "dispatcher", new DispatcherServlet());
        //设置启动顺序
        dispatcherWrapper.setLoadOnStartup(0);

        //默认的Servlet处理静态数据
//        Wrapper defaultWrapper = Tomcat.addServlet(context, "default", new DefaultServlet());

        context.addServletMappingDecoded("/*", "dispatcher");
        context.addServletMappingDecoded(ConfigHelper.getAppAssetPath() +"*", "dispatcher");
        try {
            tomcat.init();
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
        tomcat.getServer().await();;
    }
}
